<template>
    <div>
        <h2>选择被调查人</h2>
        <el-tree
            ref="tree"
            :props="props"
            :data="userTree"
            :show-checkbox="isShowCheckbox"
            node-key="id"
            @check-change="handleCheckChange"
            @node-click="handleNodeClick"
            :default-checked-keys="defaultCheckedKeys"
            :default-expanded-keys="defaultExpandedKeys"
            style="max-height: 24rem; overflow-y: auto;"
        >
        </el-tree>
    </div>
</template>

<script>
    import API from "../../api/api_user";
    import {mapActions, mapGetters} from 'vuex';
    export default {
        name: "UserSelect",
        props: {
            /**
             * 传入调查ID查询该调查已选人员
             */
            detailSurveyId: {
                type: String,
                value: ""
          }
        },
        data() {
            return {
                props: {
                    label: 'name',
                    children: 'children'
                },
                userTree: [],
                defaultExpandedKeys: [],
                defaultCheckedKeys: [],
                isShowCheckbox: true
            };
        },
        mounted() {
            let _this = this;
            if (!_this.detailSurveyId) {
                this.getUserTree();
            }
        },
        methods: {
            ...mapActions('user', [
                'setUserSelectAct'
            ]),
            handleCheckChange() {
                let _this = this;
                let res = this.$refs.tree.getCheckedNodes();
                let dest = [];
                res.forEach(val => {
                    if (val.type === "user") {
                        dest.push(val.id);
                    }
                });
                let userSelect = {
                    selectIds: dest
                };
                _this.setUserSelectAct(userSelect);
            },
            handleNodeClick(data, node) {
                if (node.data.type === "user" && this.isShowCheckbox) {
                    node.setChecked(!node.checked);
                }
            },
            getUserTree() {
                let _this = this;
                API.getUserTree().then(res => {
                    _this.userTree = res;
                    _this.defaultExpandedKeys = [];
                    _this.userTree.forEach(val => {
                        _this.defaultExpandedKeys.push(val.id);
                    })
                });
            }
        }
    }
</script>

<style scoped>

</style>
